package org.nerve.data.mining.lingpipe.classify;

import com.aliasi.classify.ConditionalClassification;
import com.aliasi.classify.LMClassifier;
import com.aliasi.util.AbstractExternalizable;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * org.nerve.data.mining.lingpipe.classify
 * Created by zengxm on 2016/7/11.
 */
public class CommonClassify {
	protected String[] categories;
	protected String dataPath;
	@SuppressWarnings("rawtypes")
	protected LMClassifier lmc;

	public CommonClassify(){}

	public CommonClassify(String dataPath) {
		this.dataPath = dataPath;

		loadData();
	}

	public String[] getCategories() {
		return categories;
	}

	public CommonClassify setDataPath(String dataPath) {
		this.dataPath = dataPath;

		loadData();
		return this;
	}

	public String getDataPath() {
		return dataPath;
	}

	protected void loadData(){
		try {
			lmc = (LMClassifier) AbstractExternalizable.readObject(new File(dataPath));
			categories = lmc.categories();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String classify(String text){
		if(lmc==null)
			throw new RuntimeException("LMClassifier is not initialized! Please call loadData() method first!");
		ConditionalClassification classification=lmc.classify(text);

		return classification.bestCategory();
	}

	/**
	 * 读取文件中的每一行，并进行分类
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public List<ClassifyBean> classify(File file) throws IOException {
		final List<ClassifyBean> beans=new CopyOnWriteArrayList<>();
		Files.readAllLines(Paths.get(file.toURI())).forEach(l-> beans.add(new ClassifyBean(classify(l), l)));

		return beans;
	}
}
